package com.dangf.interceptor;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dangf.utils.Md5Utils;

/**
 * 拦截器，验证 token
 * 
 * @author Hello_海生
 * @date 2014年3月27日
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 设置 JSON 不使用 循环引用
		JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
		
		Format formatter = new SimpleDateFormat("yyyy-MM-dd");

		String serverKey="DangF+"+formatter.format(new Date())+"+DangF";

		serverKey=Md5Utils.encryptionFor32(serverKey);
		System.out.println(serverKey+"请求地址:"+request.getServletPath());
		
		if(request.getServletPath().indexOf("/message") != -1){
			return true;
		}else if(!serverKey.equals(request.getParameter("key"))){
	        request.getRequestDispatcher("/message?msg=缺少密钥，连接出错！").forward(request, response);  
		}else if(request.getServletPath().indexOf("/user/") != -1){	//用户操作
			return true;
		}
		return true;
	}
}